/*
 * Copyright (c) 2011. c.mueller
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * The Software shall be used for Good, not Evil.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package de.altitude.cimuelle.commandhandles;

import de.altitude.cimuelle.Config;
import de.altitude.cimuelle.utils.ServerOperations;
import de.altitude.cimuelle.utils.StringUtils;
import de.altitudecustomcommands.Player;
import de.altitudecustomcommands.playerHandler;
import org.apache.log4j.Logger;

import javax.naming.ConfigurationException;
import java.util.Calendar;
import java.util.Map;

/**
 * Class description:
 * processes clientAdd events
 * User: cybernaut
 * Date: 07.10.11
 * Time: 22:08
 */
public class TypeClientAdd {
    private final static Logger LOGGER = Logger.getLogger("TypeClientAdd");

    private final playerHandler playerList;

    public TypeClientAdd(Map json, playerHandler playerList) {
        this.playerList = playerList;
        typeClientAdd(json);
    }

    private void typeClientAdd(Map json) {
        try {
            motd(json);
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }

        this.playerList.addPlayer(
                new Player((String) json.get("nickname")
                        , (String) json.get("vaporId")
                        , (String) json.get("ip")
                        , String.valueOf(json.get("port"))
                        , Integer.parseInt(String.valueOf(json.get("player")))));
    }

    private void motd(final Map line) throws ConfigurationException {
        final Config prop = Config.getInstance();
        String welcomeMessage;
        final int delay;
        final int sleepBetweenMessages;
        @SuppressWarnings({"RedundantCast"}) final
        String port = ((Number) line.get("port")).toString();

        welcomeMessage = prop.getConfigByPort(port, "welcomeMessage", "Welcome to the server.");
        delay = Integer.parseInt(prop.getConfigByPort(port, "welcomeMessage.delay", "0"));
        sleepBetweenMessages = Integer.parseInt(prop.getConfigByPort(port, "welcomeMessage.delayBetweenMessages", "0"));

        welcomeMessage = replacePlaceholder(welcomeMessage, line);

        final String playername = StringUtils.addslashes(((String) line.get("nickname")));
        final String finalWelcomeMessage = welcomeMessage;

        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(delay * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String[] welcomeMessages = finalWelcomeMessage.split("\\n");
                for (String welcomeMessage : welcomeMessages) {
                    if (prop.isDebug()) {
                        LOGGER.debug(new StringBuilder().
                                append(Calendar.getInstance().getTime()).
                                append(": ").
                                append(line.get("port")).
                                append(": ").
                                append(line.get("time")).
                                append(": Send message '").
                                append(welcomeMessage).
                                append("' to '").
                                append(playername).
                                append("'").
                                toString());
                    }
                    ServerOperations.sendServerWhisper(port, playername, welcomeMessage);
                    if (sleepBetweenMessages > 0) {
                        try {
                            Thread.sleep(sleepBetweenMessages * 1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }.start();
    }


    private String replacePlaceholder(String welcomeMessage, Map line) {
        welcomeMessage = welcomeMessage.replace("${player}", StringUtils.addslashes((String) line.get("nickname")));
        return welcomeMessage;
    }
}
